<?php

include_once F_SOURCE . 'vbc/vbc.ctrl.class.php';
include_once F_SOURCE . 'launch/launch.model.class.php';
include_once F_SOURCE . 'ads/ads.model.class.php';

/**
 * 广告投放管理CTRL类
 * 
 * @author Dean
 *
 */
class launchCtrl extends Ctrl{
	
	/**
	 * 显示投放列表
	 */
	public function show() {
		$view = new View();
		
		$pageIndex = ($_GET['pageIndex']=='' || $_GET['pageIndex']<1)?1:$_GET['pageIndex'];
		
		$launchModel = new launchModel();
		
		$number = $launchModel->countAll();
		
		$launchList = $launchModel->findAll(($pageIndex-1)*PageNum, PageNum);	
		
		$page = pageCount($number, $pageIndex, '?do=launch.show'); 
		
		$data = array(
			'op_select' => array('launch'=>"class=select"),
			'launchList' => $launchList,
			'page' => $page
		);
		
		$view->display($data, 'launch_show.html');
	}
	
	/**
	 * 查询单个投放信息
	 */
	public function info(){
		
		$view = new View();
		
		$id = $_GET['id'];
		
		$launchModel = new launchModel();
		$launchInfo = $launchModel->findOne($id);	
		
		$data = array(
			'op' => 'update',
			'op_select' => array('launch'=>"class=select"),
			'obj' => $launchInfo
		);
		
		$view->display($data, 'launch_view.html');
	}
	
	/**
	 * 跳转新增页面
	 */
	public function view(){
		$view = new View();
		
		$adid = getGetIntParam('adid');
		
		$adsModel = new adsModel();
		$adsObj = $adsModel->findOne($adid);
		
		$data = array(
			'op' => $_GET['op'],
			'obj' => $adsObj,
			'op_select' => array('launch'=>"class=select")
		);
		
		$view->display($data, 'launch_view.html');
	}
	
	/**
	 * 新增投放操作
	 * 
	 */
	public function add(){
		
		$adid = getPostIntParam('adid');
		$launchname =  getPostStringParam('name');
		$start = getPostDateParam('start');
		$end = getPostDateParam('end');
		$weight = getPostIntParam('weight');
		$clickurl = getPostStringParam('clickurl');
		$window = getPostStringParam('window');
		$status = getPostStringParam('status');
		$keywords = getPostStringParam('keywords');
		$num = getPostIntParam('num');
		$type = 'keywords';
		
		$articleList = getPostStringParam('articleList');
		$articles = $this->getUnUsedArticles($num, $articleList);
		
		$time = getNowTime();
		$createUser = $_SESSION['ads']['user']->id;
		
		$data = array(
			'name' => $launchname,
			'start' => $start,
			'end' => $end,
			'weight' => $weight,
			'click_url' => $clickurl,
			'target_window' => $window,
			'status' => $status,
			'keywords' => $keywords,
			'createTime' => $time,
			'modifyTime' => $time,
			'createUser' => $createUser,
			'ads_id' => $adid,
			'num' => $num,
			'type' => $type
		); 

		$launchModel = new launchModel();
		$insertID = $launchModel->add($data);
			
		if($insertID > 0){
			$adsModel = new adsModel();
			$adsModel->modify(array('op'=>'c'), array('id'=>$adid));
			
			$this->showMessage('?do=launch.show', 'op_success');
		}else{
			$this->showMessage('?do=launch.view&op=add', 'op_failure');
		}
	}
	
	/**
	 * 修改投放信息操作，通过投放编号
	 * 
	 */
	public function modify(){
		
		$id = getPostIntParam('id');
		$launchname =  getPostStringParam('name');
		$start = getPostDateParam('start');
		$end = getPostDateParam('end');
		$weight = getPostIntParam('weight');
		$clickurl = getPostStringParam('clickurl');
		$window = getPostStringParam('window');
		$status = getPostStringParam('status');
		$keywords = getPostStringParam('keywords');
		$num = getPostIntParam('num');
		
		$time = getNowTime();
		
		$data = array(
			'name' => $launchname,
			'start' => $start,
			'end' => $end,
			'weight' => $weight,
			'click_url' => $clickurl,
			'target_window' => $window,
			'status' => $status,
			'keywords' => $keywords,
			'modifyTime' => $time,
			'num' => $num
		);
		
		$where = array(
			'id' => $id
		);
		
		$launchModel = new launchModel();
		$number = $launchModel->modify($data, $where);
			
		if($number > 0){
			$this->showMessage('?do=launch.show', 'op_success');
		}else{
			$this->showMessage('?do=launch.view&op=add', 'op_failure');
		}
		
	}
	
	/**
	 * 新增投放操作
	 *
	 */
	public function addvbc(){
	
		$id = getPostIntParam('id');
		$launchname =  getPostStringParam('name');
		$start = getPostDateParam('start');
		$end = getPostDateParam('end');
		$weight = getPostIntParam('weight');
		$keywords = getPostStringParam('keywords');
		$otherkws = getPostStringParam('otherkws');
		$articles = getPostIntParam('articles');
// 		$intersectnum = getPostIntParam('intersectnum');
		$type = 'vbc';
	
		$time = getNowTime();
		$createUser = $_SESSION['ads']['user']->id;
	
		$data = array(
				'id' => $id,
				'name' => $launchname,
				'start' => $start,
				'end' => $end,
				'keywords' => $keywords,
				'otherkws' => $otherkws,
				'articles' => $articles,
// 				'intersectnum' => $intersectnum,
				'createTime' => $time,
				'createUser' => $createUser,
				'type' => $type
		);
	
		$launchModel = new launchModel();
		$insertID = $launchModel->add($data);
			
		if($insertID > 0){
			$launchModel = new launchModel();
			$launchModel->import_modify(array('op'=>'c'), array('id'=>$id));
			
			$this->writeArticleFile($keywords);		//	update used articles
				
			$this->showMessage('?do=launch.show', 'op_success');
		}else{
			$this->showMessage('?do=launch.view&op=add', 'op_failure');
		}
	}
	
	/**
	 * 删除操作，通过编号
	 * 
	 */
	public function delete(){
		
		$id = intval($_GET['id'])>0?intval($_GET['id']):0;
		
		if($id<1){
			$this->showMessage('?do=launch.show', 'op_wrong_id');
		}
		
		$data = array(
			'id' => $id
		);
		
		$launchModel = new launchModel();
		$success = $launchModel->delete($data);
		
		if($success > 0){
			$this->showMessage('?do=launch.show', 'op_success');
		}else{
			$this->showMessage('?do=launch.show', 'op_failure');
		}
	}

	public function getKeywordsAds(){
		
		global $memcache;
		
		$key = "keywords_ads_".date('Ymd');
		$memKey = md5($key);
		
		$content = $memcache->get($memKey);
		
//		$file = F_ROOT.'kws_ads/kwlisting.txt';
		$callback = getGetStringParam('callback');
//		$content = file_get_contents($file);
	
		$hasContent = false;
		if(empty($content)){
			$content = $this->getKeywordsFromDB();
//			$this->writeKwsFile($file, $content);
			$memcache->set($memKey, $content, MEMCACHE_COMPRESSED, 1800);
			if($_GET['debug_mem']){
				echo 'get content by DB <br />';
			}
			
			echo checkCallBack($callback, $content);
			exit;
		}
		
//		$contentArr = json_decode($content, true);
//		$fileTime = $contentArr['time'];
//		
//		if (!$this->checkTime($fileTime)){
//			$content = $this->getKeywordsFromDB();
//			$this->writeKwsFile($file, $content);
//			echo checkCallBack($callback, $content);
//			exit;
//		}
		
//		echo checkCallBack($callback, $contentArr['content']);
		echo checkCallBack($callback, $content);
		exit;
	}
	
	private function getKeywordsFromDB(){
		$launchModel = new launchModel();
		$kwAds = $launchModel->findEffectByType('keywords'); 
		
		$kwList = array();
		if (is_array($kwAds)){
			foreach ($kwAds as $ads) {
				$HDID = $ads->id;
				$adid = $ads->ads_id;
				$tpl = $ads->tpl;
				$keywords = $ads->keywords;
				$kws = explode(',', $keywords);
				foreach ($kws as $kw){
					if (empty($kw))continue;
					$kw = strtolower($kw);	// let KW to lower edit by 2012-5-29
					if(!key_exists($kw, $kwList)){
						if(stripos($HDID, 'HD')===false){
							$launchInfo = $launchModel->findLaunchIDByHDID($adid);
							if(!isset($launchInfo->id))continue;
							$launchID = $launchInfo->id;
							$callValue = "c=944&l=$launchID&b=$adid";
							$fileContent = file_get_contents("http://hfm.adsame.com/s?z=hfm&$callValue");
							if(stripos($fileContent, "document.write")!==false){
								$kwList[$kw] = $callValue;
							}else{
								$kwList[$kw] = "c=998&l=$launchID&b=$adid";
							}
						}else{
								$kwList[$kw] = "id=$HDID&es=1&tpl=$tpl";
						}
					}
				}
			}
		}
		
		return json_encode($kwList);
	}
	
	private function writeKwsFile($file, $json){
		$time = getNowTime();
		
		$arr = array(
			'time' => $time,
			'content' => $json		
		);
		
		$arr = json_encode($arr);
		
		file_put_contents($file, $arr, LOCK_EX);
	}
	
	private function checkTime($time){
		if(empty($time))return false;
		
		$timestamp = strtotime($time);
		if($timestamp==false)return false;
		
// 		$fileDate = date('Y-m-d', $timestamp);
// 		$nowDate = date('Y-m-d');

		$now = strtotime('now');
		
// 		if($fileDate==$nowDate){
		if($now - $timestamp < 1){
			return true;
		}else{
			return false;
		}
	}
	
	public function moreKeywordsFromBaidu(){
		
		$id = getGetIntParam('id');
		$keywords = getGetStringParam('keywords');
		$kwArr = explode(',', $keywords);
		
		$solrUrl = include F_CONF.'solr.config.php';
		$host = include F_CONF . 'host.'.Env_Config.'.config.php';
		//more keywords
		$otherKwArr = array();
		foreach ($kwArr as $kw){
			
			$url = $host.'baiduapi/';
			$limit = 5;
			$otherKws = readBaiduKeywords($url, $kw, $limit);
			
			$temp = array();
			foreach ($otherKws as $other){
				$temp[] = $other['kw'];
			}
			
			$otherKwArr = array_merge($otherKwArr, $temp);
		}
		
		// find file number by solr
		$fileArr = array();
		foreach ($kwArr as $kw){
			
			$files = searchBySolr($solrUrl['article'], $kw);
			
			$fileArr = array_merge($fileArr, $files);
			$fileArr = array_unique($fileArr);
		}
		
		// get used articles number
		$intersectnum = $this->getUsedArticleList($kwArr, $fileArr);
// 		$articles =$this->getUsedArticleList();
// 		$articles = explode(',', $articles);
// 		if(is_array($fileArr)){
// 			$intersectArr = array_intersect($articles, $fileArr);
// 		}else{
// 			$intersectArr = array();
// 		}
		
		$arr = array();
		$arr['kws'] = implode(',', $otherKwArr);
		$arr['articlenum'] = count($fileArr);
		$arr['articleList'] = implode(',', $fileArr);
		$arr['intersectnum'] = $intersectnum; // count($intersectArr);
		
		echo json_encode($arr);
	}
	
	public function searchArticles(){
		
		$id = getGetIntParam('id');
		$keywords = getGetStringParam('keywords');
		$kwArr = explode(',', $keywords);
		
		$solrUrl = include F_CONF.'solr.config.php';
		
		// find file number by solr
		$fileArr = array();
		foreach ($kwArr as $kw){
				
			$files = searchBySolr($solrUrl['article'], $kw);
				
			$fileArr = array_merge($fileArr, $files);
			$fileArr = array_unique($fileArr);
		}
		
		$arr = array();
		$arr['articlenum'] = count($fileArr);
		echo json_encode($arr);
	}
	
	private function getUsedArticleList($kws, $articles){
		
		$vbcCtrl = new vbcCtrl();
		$usedArticleList = $vbcCtrl->getUsedArticleListFromDB();
		
		$canUsedArticles = array_intersect($articles, $usedArticleList);
		
		return count($canUsedArticles);
		
// 		$launchModel = new launchModel();
		
// 		$launchArr = array();
// 		foreach ($kws as $kw){
// 			$list = $launchModel->findByKws('vbc', $kw);
// 			foreach ($list as $row){	
// 				$launchArr[$row->id] = $row->num;
// 			}
// 		}
		
// 		$i = 0;
// 		foreach ($launchArr as $value){
// 			$i += intval($value);
// 		}
		
// 		return $i;
		
// 		$file = F_ROOT.'kws_ads/usedartcle.txt';
		
// 		$articles = file_get_contents($file);
		
// 		$hasContent = false;
// 		if(empty($articles)){
// 			$articles = $this->getArticleListFromDB();
// 			file_put_contents($file, $articles, LOCK_EX);
// 		}
		
// 		return $articles;
	}
	
	private function getArticleListFromDB(){
		
		$launchModel = new launchModel();
		$vbcAds = $launchModel->findAllByType('vbc');
		
		$articleList = array();
		if (is_array($vbcAds)){
			foreach ($vbcAds as $ads) {
				$adid = $ads->id;
				$articles = $ads->articles;
				$articles = explode(',', $articles);
				$articleList = array_merge($articleList, $articles);
			}
		}
		
		$articleList = array_unique($articleList);
		return implode(',', $articleList);
	}
	
	private function writeArticleFile($arr){
		
		$file = F_ROOT.'kws_ads/usedartcle.txt';
		
		$articles = file_get_contents($file);
		
		if(empty($articles)){
			file_put_contents($file, $arr, LOCK_EX);
		}else{
			
			$articles = array_merge($arr, $articles);
			$articles = array_unique($articles);
			
			file_put_contents($file, json_encode($articles), LOCK_EX);
		}
	}
	
	
	public function getVBCAds(){
		global $memcache;
		
		$id = getGetStringParam('id');
		$callback = getGetStringParam('callback');
		
		$key = 'vbc_ads_'.$id.'_'.date('Ymd');
		$memKey = md5($key);
		$json = $memcache->get($memKey);
		
		if(!isset($json) || empty($json)){
			$json = array();
			$launchModel = new launchModel();
			$launchInfo = $launchModel->findByArticleID($id);
			$AdIDs = $launchInfo->ad_ids;
			if(!isset($AdIDs) || $AdIDs==''){
				$json = json_encode($json);
				echo checkCallBack($callback, $json);
				exit;
			}
			
			$adsModel = new adsModel();
			$list = $adsModel->findAdsByAdsIDs($AdIDs);
			$positionArr = include F_CONF.'position.config.php';
			
			foreach ($list as $value) {
				$ads_position = explode('-', $value->name);
				$adsID = $value->id;
				if(!isset($ads_position[1]))continue;
				foreach ($positionArr as $key=>$value){
					if($ads_position[1]==$key){
						$importLaunch = $launchModel->findLaunchIDByHDID($adsID);
						$json[$ads_position[1]] = "c=$value&l={$importLaunch->id}&b={$adsID}";
					}
				}
			}
			
			if($_GET['debug_mem']){
				echo 'get content by DB <br />';
			}
			
			$json = json_encode($json);
			$memcache->set($memKey, $json, MEMCACHE_COMPRESSED, 1800);
		}
		
		echo checkCallBack($callback, $json);
	}
	
	public function getKWHTML(){
		$id = getGetStringParam('id');
		
		global $memcache;
		
		$key = 'get_kw_html_'.$id.'_'.date('Ymd');
		$memKey = md5($key);
		
		$content = $memcache->get($memKey);
		if(!isset($content) || empty($content)){
			$launchModel = new launchModel();
			$kwInfo = $launchModel->findOne( $id );
			$imgInfo = $launchModel->getKWImgByID($id);
			if(!isset($imgInfo->id)){
				echo '';
				exit ;
			}
			
			$action_host = "http://".$_SERVER['HTTP_HOST']."/upload_file/image/";
			
			$htmlContent = file_get_contents(F_ROOT.'template/kw_show_mockup_' . $kwInfo->tpl . '.html');
			
			$htmlContent = str_replace("IMG_HOLDER", replaceForScript($action_host.$imgInfo->img), $htmlContent);
			$htmlContent = str_replace("TITLE_HOLDER", replaceForScript($imgInfo->img_title), $htmlContent);
			$htmlContent = str_replace("DESC_HOLDER", replaceForScript($imgInfo->img_desc), $htmlContent);
			$htmlContent = str_replace("PRICE_HOLDER", replaceForScript($imgInfo->img_price), $htmlContent);
			
			if(stripos($imgInfo->img_outurl, "http://")===false){
				$imgInfo->img_outurl = "http://".$imgInfo->img_outurl;
			}
			$htmlContent = str_replace("OUT_HOLDER", replaceForScript($imgInfo->img_outurl), $htmlContent);
			
			$a = 's'.rand(1000, 9999);
			
			$htmlContent = trim($htmlContent);
			$htmlContent = str_replace( array( "\n", "\r" ), ' ', $htmlContent );
			$js = "var $a = '$htmlContent'; eval('document.write($a)');";
			
			$js = trim($js);
			
			if($_GET['debug_mem']){
				echo 'get content by DB <br />';
			}
			
			$memcache->set($memKey, $js, MEMCACHE_COMPRESSED, 1800);
			echo $js;
			exit;
		}
		
		echo $content;
		exit;
	}
}


?>